
const fs = require('fs');
const path = require('path');

module.exports = async ctx => {
    try {
        const ldteprojectpath = ctx.request.req.headers.ldteprojectpath
        const dir = path.join(ldteprojectpath, ctx.request.body.path);
        const list = await readdir(dir);
        ctx.status = 200;
        ctx.body = await getFile(ldteprojectpath, dir, list)
    } catch (error) {
        ctx.status = error.code || 500;
        ctx.body = error;
    }
}

/** 查询文件夹内容 */
function readdir(dir) {
    return new Promise((resolve, reject) => {
        fs.readdir(dir, (err, files) => {
            if (err) {
                reject(err);
            } else {
                resolve(files);
            }
        })
    })
}

/** 查询文件信息 */
async function getFile(ldteprojectpath, dir, list) {
    const sum = [];
    for (let i = 0; i < list.length; i++) {
        const stat = await fs.promises.stat(path.join(dir, list[i]));
        sum.push({
            isFile: stat.isFile(),
            name: list[i],
            path: path.relative(ldteprojectpath, path.join(dir, list[i])),
            extension: stat.isFile() ? list[i].split('.').pop() : undefined
        });
    }
    return sum;
}